import '../../util/_base_export.dart';
import '../../util/_view_export.dart';
import 'page_sub_category.dart';
import 'page_controller/shop_scroll_coordinator.dart';
import 'page_controller/shop_scroll_controller.dart';
import '../../blocs/menu.dart';
import '../../blocs/cart.dart';

MediaQueryData? mediaQuery;
double? statusBarHeight;
double? screenHeight;

class ShopPage extends StatefulWidget {
  ShopPage({Key? key}) : super(key: key);

  @override
  _ShopPageState createState() => _ShopPageState();
}

class _ShopPageState extends State<ShopPage> with SingleTickerProviderStateMixin {
  ///页面滑动协调器
  late ShopScrollCoordinator _shopCoordinator;
  ShopScrollController? _pageScrollController;

  late TabController _tabController;

  final double _sliverAppBarInitHeight = 1000;
  final double _tabBarHeight = 66.h;
  double? _sliverAppBarMaxHeight;

  GlobalKey cartKey = GlobalKey();
  GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();
  ValueChanged _onChanged = (val) => print(val);

  @override
  void initState() {
    super.initState();
    _shopCoordinator = ShopScrollCoordinator();
    _tabController = TabController(
        vsync: this,
        length: Provider.of<MenuBloc>(context, listen: false).sub_category_list.length);
  }

  @override
  Widget build(BuildContext context) {
    mediaQuery ??= MediaQuery.of(context);
    screenHeight ??= mediaQuery?.size.height;
    statusBarHeight ??= mediaQuery?.padding.top;

    _sliverAppBarMaxHeight ??= screenHeight;
    _pageScrollController ??=
        _shopCoordinator.pageScrollController((_sliverAppBarMaxHeight! - _sliverAppBarInitHeight));

    _shopCoordinator.pinnedHeaderSliverHeightBuilder ??= () {
      return statusBarHeight! + kToolbarHeight + _tabBarHeight;
    };
    var ll_banners = [];
    if ((AppSession.appUtil.data['home_data'] ?? {}).isNotEmpty)
      ll_banners = AppSession.appUtil.data['home_data']['banner_cate2'];
    return Material(
      child: Listener(
        onPointerUp: _shopCoordinator.onPointerUp,
        child: CustomScrollView(
          controller: _pageScrollController,
          physics: ClampingScrollPhysics(),
          slivers: <Widget>[
            SliverAppBar(
                backgroundColor: Colors.white,
                brightness: Brightness.light,
                leadingWidth: 33.w,
                pinned: true,
                leading: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    Navigator.pop(context);
                  },
                  child: Container(
                    child: Icon(
                      Icons.chevron_left,
                      color: AppColor.blackMain,
                      size: 32,
                    ),
                  ),
                ),
                title: Container(
                  width: 266.w,
                  padding: EdgeInsets.only(left: 0.w, right: 30.w),
                  child: FormBuilder(
                    // context,
                    key: _fbKey,
                    autovalidateMode: AutovalidateMode.always,
                    initialValue: {
                      'keyword': '',
                    },
                    enabled: false,
                    child: Container(
                      padding: EdgeInsets.only(
                        left: 10.w,
                      ),
                      child: FormBuilderTextField(
                        name: "keyword",
                        decoration: InputDecoration(
                          hintText: "请输入想要的产品",
                          contentPadding: EdgeInsets.all(10.0),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(30.0)),
                          ), //former builder⾥的弧度要⽐外边⼩
                          suffixIcon: Container(
                            height: 26.h,
                            width: 60.w,
                            margin: EdgeInsets.symmetric(vertical: 5.h, horizontal: 5.w),
                            decoration: BoxDecoration(
                              color: AppColor.yellowMain,
                              borderRadius: BorderRadius.all(Radius.circular(30.0)),
                            ),
                            child: TextButton(
                              onPressed: () async {
                                FocusScope.of(context).requestFocus(FocusNode());
                                _fbKey.currentState?.save();

                                if ((_fbKey.currentState?.value['keyword'] ?? '').isNotEmpty) {
                                  var lm_param = {
                                    "keyword": _fbKey.currentState?.value['keyword'],
                                  };
                                  var lv_param = Uri.encodeQueryComponent(jsonEncode(lm_param));
                                  App.router.navigateTo(context, '/product_list?param=${lv_param}');
                                } else {
                                  AppPopupService.showAlertSimple('I', '注意啦', '产品关键词不能为空',
                                      iv_duration: Duration(seconds: 3));
                                }
                              },
                              // highlightColor: const Color(0x55FF8A80),
                              // splashColor: const Color(0x99FF8A80),
                              style: ButtonStyle(
                                overlayColor: MaterialStateColor.resolveWith((states) => Color(0x55FF8A80)),
                              ),
                              child: Text(
                                '搜索',
                                style: TextStyle(color: AppColor.blackMain, fontSize: 12.sp),
                              ),
                            ),
                          ),
                          prefixIcon: Icon(Icons.search, color: AppColor.yellowMain),
                        ),
                        onChanged: _onChanged,
                        // valueTransformer: (text) => num.tryParse(text),
                        // validators: [],
                        keyboardType: TextInputType.text,
                      ),
                    ),
                  ),
                ),
                actions: [
                  Container(
                    margin: EdgeInsets.only(right: 21.w),
                    child: Consumer<CartBloc>(
                      builder: (context, _cart, child) => Builder(
                        builder: (context) {
                          return GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () {
                              if (_cart.amount == 0)
                                AppPopupService.showAlertSimple(
                                    'I', '购物车是空的', '请先选择商品加入购物车，然后再结账哦');
                              else
                                App.router.navigateTo(context, AppRoutes.orderCart);
                            },
                            child: Badge(
                              badgeColor: Colors.red,
                              toAnimate: true,
                              shape: BadgeShape.circle,
                              position: BadgePosition.topEnd(top: -2, end: -5),
                              borderRadius: BorderRadius.circular(20),
                              animationType: BadgeAnimationType.scale,
                              child: Image.asset(
                                'assets/order/cart_circle.png',
                                key: cartKey,
                              ),
                              badgeContent: Text(_cart.amount.toString(),
                                  style: TextStyle(color: Colors.white)),
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ]),
            SliverPersistentHeader(
              pinned: false,
              floating: true,
              delegate: _SliverAppBarDelegate(
                maxHeight: 160.h,
                minHeight: 160.h,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h),
                  height: 160.h,
                  width: 343.w,
                  child: Swiper(
                    key: ObjectKey(ll_banners),
                    autoplay: true,
                    autoplayDelay: 3000,
                    viewportFraction: 0.99999,
                    itemCount: ll_banners.length,
                    itemBuilder: (BuildContext context, int index) {
                      var _currentBanner= {};
                      if (ll_banners.isNotEmpty) {
                        _currentBanner = (ll_banners.length != 0) ? ll_banners[index] : {};
                      }
                      return ClipRRect(
                        borderRadius: BorderRadius.circular(6),
                        child: GestureDetector(
                          onTap: () {
                            try {
                              switch (ll_banners[index]['banner_navitype']) {
                                case 2:
                                  // final WebView = new Webview();
                                  //flutterWebViewPlugin.close();
                                  var encodedUrl = Uri.encodeComponent(ll_banners[index]['banner_url']);
                                  App.router.navigateTo(context, '/webview/$encodedUrl');
                                  break;
                              }
                            } catch (exception, stackTrace) {
                              print(exception);
                              print(stackTrace);
                            }
                          },
                          child: CachedNetworkImage(
                            imageUrl: ll_banners[index]['banner_image'],
                            fit: BoxFit.cover,
                          ),
                        ),
                      );
                      // ),
                    },
                    pagination: new SwiperPagination(
                      builder: SwiperPagination.rect,
                    ),
                    control: new SwiperControl(
                      color: Colors.transparent,
                    ),
                  ),
                ),
              ),
            ),
            SliverPersistentHeader(
              pinned: true,
              floating: false,
              delegate: _SliverAppBarDelegate(
                maxHeight: _tabBarHeight,
                minHeight: _tabBarHeight,
                child: Container(
                  padding: EdgeInsets.symmetric(
                    vertical: 18.h,
                  ),
                  color: Colors.white,
                  child: TabBar(
                    labelColor: Color(0xffFF9F05),
                    controller: _tabController,
                    isScrollable: true,
                    unselectedLabelColor: Color(0xff808080),
                    indicatorSize: TabBarIndicatorSize.label,
                    indicator: BoxDecoration(
                        borderRadius: BorderRadius.circular(15.w), color: Color(0xffFFF8E6)),
                    tabs:
                        Provider.of<MenuBloc>(context, listen: false).sub_category_list.map((item) {
                      return Tab(
                        child: Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(15.w),
                          ),
                          padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 4.h),
                          child: Center(
                            child: Text(item['cate2_name'], style: TextStyle(fontSize: 15.sp)),
                          ),
                        ),
                      );
                    }).toList(),
                  ),
                ),
              ),
            ),
            SliverFillRemaining(
              child: TabBarView(
                controller: _tabController,
                children:
                    Provider.of<MenuBloc>(context, listen: false).sub_category_list.map((item) {
                  return SubMenuPage(
                      tabController: _tabController,
                      shopCoordinator: _shopCoordinator,
                      cate3_list: item['cate3s']);
                }).toList(),
              ),
            )
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
    _pageScrollController?.dispose();
  }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SliverAppBarDelegate({
    required this.minHeight,
    required this.maxHeight,
    required this.child,
  });

  final double minHeight;
  final double maxHeight;
  final Widget child;

  @override
  double get minExtent => this.minHeight;

  @override
  double get maxExtent => max(maxHeight, minHeight);

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return SizedBox.expand(child: child);
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return maxHeight != oldDelegate.maxHeight ||
        minHeight != oldDelegate.minHeight ||
        child != oldDelegate.child;
  }
}
